package com.zy.recursion;

import com.zy.ListNode;

/**
 * @description: 合并两个有序链表的递归解法，另一个版本的解法参见 TestLink # mergeTwoLists
 * @author: zhaoyi
 * @create: 2019-09-08 21:42
 * https://leetcode-cn.com/explore/orignial/card/recursion-i/260/conclusion/1229/
 **/

public class MergeLink {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode result;
        if (l1.val <= l2.val) {
            result = l1;
        } else {
            result = l2;
        }
        recursion(l1, l2);
        return result;
    }

    private void recursion(ListNode l1, ListNode l2) {

        if (l1.val <= l2.val) {
            if (l1.next == null) {
                l1.next = l2;
                return;
            } else if (l1.next.val <= l2.val) {
                recursion(l1.next, l2);
            } else {
                ListNode next = l1.next;
                l1.next = l2;
                recursion(next, l2);
            }
        } else {
            if (l2.next == null) {
                l2.next = l1;
                return;
            } else if (l1.val > l2.next.val) {
                recursion(l1, l2.next);
            } else {
                ListNode next = l2.next;
                l2.next = l1;
                recursion(l1, next);
            }
        }
    }

}
